import { AddForm } from './add-form';
import { DoneForm } from './done-form';
import Markdown from 'react-markdown';
import { Toaster } from '@/components/ui/toast';
import { Button } from '@/components/ui/button';
import Link from 'next/link';
import { ArrowLeft } from 'lucide-react';
import SignoutButton from '../../SignoutButton';
import { nile } from '@/app/api/[...nile]/nile';

// Forcing to re-evaluate each time.
// This guarantees that users will only see their own data and not another user's data via cache
export const dynamic = 'force-dynamic';
export const dynamicParams = true;
export const revalidate = 0;
export const fetchCache = 'force-no-store';

// Todo: replace "raw" context setting with nicer SDK
export default async function Page({
  params,
}: {
  params: Promise<{ tenantid: string }>;
}) {
  const tenantId = (await params).tenantid;
  // Here we are getting a connection to a specific tenant database for the current usr
  // if we already got such connection earlier, it will reuse the existing one
  const tenantNile = await nile.withContext({
    tenantId,
  });

  console.log(
    'showing todos for user ' +
      nile.getContext().userId +
      ' for tenant ' +
      nile.getContext().tenantId,
  );
  const todos = await tenantNile
    .query('select * from todos order by title')
    .catch((e: Error) => {
      console.error(e);
    }); // no need for where clause because we previously set Nile context
  // Get tenant name doesn't need any input parameters because it uses the tenant ID and user token from the context
  const tenant = await tenantNile.tenants.get();

  if (tenant instanceof Response) {
    return (
      <div>
        Unable to retrieve tenant <SignoutButton />
      </div>
    );
  }

  if (!todos) {
    return (
      <div className="flex flex-col gap-4">
        <div className="rounded-xl bg-destructive px-6 py-3 text-3xl text-white">
          Unable to get todos. Does your database have a todos table?
        </div>
      </div>
    );
  }
  return (
    <div className="flex flex-col gap-4">
      <Link href="/tenants">
        <Button variant="link" size="sm" className="pl-0">
          <ArrowLeft />
          (Back to tenant selection)
        </Button>
      </Link>
      <h2 className="text-xl uppercase">{tenant.name}&apos;s Todos</h2>
      <div className="h-px w-full bg-primary opacity-30" />
      <div className="flex flex-col gap-8 px-4">
        <AddForm tenantid={tenantId} />
        <table>
          <caption className="pb-4 text-xs">
            Estimates are generated by a very smart Llama 🦙 (3.1 405B)
          </caption>
          <tbody>
            <tr>
              <th style={{ width: '60%' }}>Task</th>
              <th>AI estimate</th>
            </tr>
            {todos.rows.map((todo: any) => (
              <tr key={todo.id} className="border-px">
                <td style={{ width: '60%' }} className="py-1">
                  <DoneForm tenantId={tenantId} todo={todo} />
                </td>
                <td>
                  <Markdown>
                    {todo.estimate
                      ? String(todo.estimate)
                      : 'No estimate found'}
                  </Markdown>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        <Toaster />
      </div>
    </div>
  );
}
